{% extends '../_base.html' %}

<!-- display sidebar on left -->
{% set __sidebar_left__ = true %}

{% block nav %} /user/ {% endblock %}

{% block title %}{{ _('Sponsor') }}{% endblock %}

{% block head %}

<style>
.x-discuss-visible {
    display: block;
}
</style>

<script>

$(function () {
    $('#{{ adperiod.id }}').addClass('uk-active');
});

var
    END_DAY = '{{ adperiod.end_at }}',
    TODAY = '{{ today }}';

function showMaterialForm() {
    $('#x-add-material').hide();
    $('#x-material-form').show();
}

function _showLarge(url) {
    var lightbox = UIkit.lightbox.create([{
        source: url,
        type: 'image'
    }]);
    lightbox.show();
}

function deleteAdMaterial(admId) {
    UIkit.modal.confirm('Are you sure you want to delete it?', function() {
        postJSON('/api/admaterials/' + admId + '/delete', {}, function (err) {
            if (err) {
                _alert(err.message || err);
            } else {
                refresh();
            }
        });
    });
}

var g_status = {
    "ACTIVE": "<span class=\"uk-text-success\"><i class=\"uk-icon-play-circle-o\"></i> " + "{{ _('Active') }}" + "</span>",
    "PENDING": "<span class=\"uk-text-warning\"><i class=\"uk-icon-pause-circle-o\"></i> " + "{{ _('Pending') }}" + "</span>",
    "EXPIRED": "<span class=\"uk-text-danger\"><i class=\"uk-icon-stop-circle-o\"></i> " + "{{ _('Expired') }}" + "</span>"
}

function _getStatus(status) {
    return g_status[status];
}

var IMAGE_WIDTH = parseInt('{{ adperiod.adslot.width }}');
var IMAGE_HEIGHT = parseInt('{{ adperiod.adslot.height }}');
var IMAGE_MAX_SIZE = IMAGE_WIDTH * IMAGE_HEIGHT / 2;
var IMAGE_MAX_SIZE_KB = Math.floor(IMAGE_MAX_SIZE / 1024);

var imageData = null;

function _alert(msg) {
    UIkit.modal.alert(msg);
}

function _processImageFile(file, callback) {
    if (file.type!=='image/jpeg') {
        return _alert('Uploaded image must be JPEG format!');
    }
    var reader = new FileReader();
    reader.onload = function(e) {
        var
            data = e.target.result;
            index = data.indexOf(';base64,');
        if ((index >= 0) && (index < 100)) {
            var theData = data.substring(index + 8);
            if (theData.length * 0.75 > IMAGE_MAX_SIZE) {
                return _alert('Image file is exceeded for ' + IMAGE_MAX_SIZE_KB + ' kb.');
            }
            var theImage = new Image();
            theImage.onload = function () {
                var
                    w = this.width,
                    h = this.height;
                if (w !== IMAGE_WIDTH || h !== IMAGE_HEIGHT) {
                    return _alert('Image size is NOT exactly ' + IMAGE_WIDTH + ' x ' + IMAGE_HEIGHT);
                }
                imageData = theData;
                callback({
                    image: data,
                    data: theData
                });
            };
            theImage.onerror = function () {
                return _alert('Not a valid image file!');
            };
            theImage.src = data;
        } else {
            return _alert('Browser does not support data URL!');
        }
    };
    reader.readAsDataURL(file);
}

$(function () {
    var
        $preview = $('#image-preview'),
        $form = $('#x-material-form'),
        $file = $form.find('input[name=file]'),
        $url = $form.find('input[name=url]'),
        $start_at = $form.find('input[name=start_at]'),
        $end_at = $form.find('input[name=end_at]'),
        $keywords = $form.find('input[name=keywords]'),
        $weight = $form.find('input[name=weight]'),
        $cancel = $form.find('button.x-cancel');

    // watch file change:
    $('#file').change(function (evt) {
        evt.preventDefault();
        // clear:
        imageData = null;
        $preview.css('background-image', 'none');
        var f = $('#file').val();
        if (f === '') {
            // user cancelled selected file:
            return;
        }
        try {
            var file = $('#file').get(0).files[0];
            _processImageFile(file, function (r) {
                imageData = r.data;
                $preview.css('background-image', 'url(' + r.image + ')');
            });
        }
        catch (e) {
            UIkit.modal.alert('Error when process file: ' + e);
        }
    });

    $form.submit(function (e) {
        e.preventDefault();
        var data = {
            image: imageData,
            url: $url.val().trim(),
            start_at: $start_at.val().trim(),
            end_at: $end_at.val().trim(),
            keywords: $keywords.val().trim(),
            weight: parseInt($weight.val().trim() || '100')
        };
        // check:
        if (data.image === null) {
            return _alert('Please select an image file.');
        }
        if (data.url === '' || (data.url.indexOf('http://') !== 0 && data.url.indexOf('https://') !== 0)) {
            return _alert('Invalid URL.');
        }
        if (data.start_at !== '' && data.end_at !== '' && data.start_at >= data.end_at) {
            return _alert('End date must be greater than start date.');
        }
        if (isNaN(data.weight) || data.weight <= 0 || data.weight > 100) {
            return _alert('Invalid weight.');
        }
        if (data.start_at === '') {
            delete data.start_at;
        }
        if (data.end_at === '') {
            delete data.end_at;
        }

        data.keywords = _.filter(_.map(data.keywords.split(','), function (s) {
            return s.trim();
        }), function (s) {
            return s !== '';
        }).join(',');

        $form.postJSON('/api/adperiods/{{ adperiod.id }}/admaterials', data, function (err, r) {
            if (err) {
                return _alert('Create material failed: ' + (err.message || err.error));
            }
            location.assign('/sponsor/adperiod/{{ adperiod.id }}');
        });
    });

    $cancel.click(function () {
        location.assign('/sponsor/adperiod/{{ adperiod.id }}');
    });
});
</script>
{% endblock %}

{% block sidebar_left_content %}
    <h3>{{ _('AD Subscriptions') }}</h3>
    <ul class="uk-nav uk-nav-side">
        <li class="uk-nav-header">Active AD Slots</li>
    </ul>
    <ul class="uk-nav uk-nav-side" style="margin-right:-15px;">
        {% for p in adperiods %}
        <li id="{{ p.id }}">
            <a href="/sponsor/adperiod/{{ p.id }}"><i class="uk-icon-photo"></i> {{ p.adslot.name }} ({{ p.adslot.width }} x {{ p.adslot.height }})</a>
        </li>
        {% endfor %}
        <!--
        <li id="buyAdPeriod">
            <a href="/sponsor/buy"><i class="uk-icon-plus"></i> New Subscription</a>
        </li>
        -->
    </ul>
    <div class="x-placeholder"></div>
{% endblock %}

{% block content %}

    <div class="x-ad-subscription uk-panel uk-panel-box">
        <h3 class="uk-panel-title">AD Subscription Info</h3>
        <hr>
        <p>AD slot: {{ adperiod.adslot.name }}</p>
        <p>AD size: {{ adperiod.adslot.width }} x {{ adperiod.adslot.height }}</p>
        <p>{{ _('Started at') }}: {{ adperiod.start_at }}</p>
        <p>{{ _('Expires at') }}: <span id="x-adperiod-expires"></span></p>
        <script>
            var m = moment('{{ adperiod.end_at }}');
            $('#x-adperiod-expires').text(m.subtract(1, 'days').format('YYYY-MM-DD'));
        </script>
        <p>{{ _('Status') }}: <span id="x-adperiod-status"></span></p>
        <script>
            $('#x-adperiod-status').html(_getStatus('{{ adperiod.status }}'));
        </script>
    </div>

    <div class="x-placeholder"></div>

    <h3>AD Materials</h3>

    <table class="uk-table uk-table-hover">
        <thead>
            <tr>
                <th width="15%">{{ _('Image') }}</th>
                <th width="30%">{{ _('URL') }}</th>
                <th width="10%">{{ _('Start from') }}</th>
                <th width="10%">{{ _('End at') }} ({{ _('Exclusive') }})</th>
                <th width="10%">{{ _('Keywords') }}</th>
                <th width="10%">{{ _('Weight') }}</th>
                <th width="10%">{{ _('Status') }}</th>
                <th width="5%">{{ _('Action') }}</th>
            </tr>
        </thead>
        <tbody>
            {% for m in admaterials %}
            <tr>
                <td>
                    <a href="#0" onclick="_showLarge('{{ __cdn__ }}/files/attachments/{{ m.cover_id }}')"><img src="{{ __cdn__ }}/files/attachments/{{ m.cover_id }}/s"></a>
                </td>
                <td><a href="{{ m.url }}" target="_blank">{{ m.url }}</a></td>
                <td>{{ m.start_at }}</td>
                <td>{{ m.end_at }}</td>
                <td>{{ m.keywords }}</td>
                <td>{{ m.weight }}</td>
                <td>
                    <script>
                        document.write(_getStatus('{{ m.status }}'));
                    </script>
                </td>
                <td>
                    <a href="javascript:deleteAdMaterial('{{ m.id }}')" title="Delete"><i class="uk-icon-trash"></i></a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

    <div id="x-add-material">
        <button class="uk-button uk-button-primary" onclick="showMaterialForm()"
            {% if admaterials.length >= 10 %}
            disabled
            {% endif %}
        >Add Ad Material</button></div>

    <div class="x-placeholder"></div>

    <form id="x-material-form" class="uk-form uk-form-stacked" style="display: none">
        <legend>{{ _('Add New AD Material') }}</legend>
        <fieldset>
            <div class="uk-alert uk-alert-danger uk-hidden"></div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Image') }}:</label>
                <div class="uk-form-controls">
                    <div id="image-preview" style="border: 1px solid #ccc; width:{{ adperiod.adslot.width }}px; height:{{ adperiod.adslot.height }}px; background-size:cover;"></div>
                </div>
                <div class="uk-form-controls">
                    <input id="file" name="file" type="file">
                    <p>The uploaded image must be JPG format.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('URL') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-link"></i>
                        <input name="url" type="text" placeholder="https://" class="uk-form-width-large">
                    </div>
                    <p>The landing page URL. https is preferred.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Start from') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-calendar"></i>
                        <input name="start_at" type="text" placeholder="Now" class="uk-form-width-medium" data-uk-datepicker="{format:'YYYY-MM-DD'}">
                    </div>
                    <p>Optional: the AD will display from the specific date.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('End at') }} ({{ _('Exclusive') }}):</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-calendar"></i>
                        <input name="end_at" type="text" placeholder="Forever" class="uk-form-width-medium" data-uk-datepicker="{format:'YYYY-MM-DD'}">
                    </div>
                    <p>Optional: the AD will display only before the specific date.</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Keywords') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-sliders"></i>
                        <input name="keywords" type="text" placeholder="Keywords seperated by ," class="uk-form-width-medium">
                    </div>
                    <p>Optional: the keywords of the AD. Seperated by ,</p>
                </div>
            </div>
            <div class="uk-form-row">
                <label class="uk-form-label">{{ _('Weight') }}:</label>
                <div class="uk-form-controls">
                    <div class="uk-form-icon">
                        <i class="uk-icon-sliders"></i>
                        <input name="weight" type="text" placeholder="100" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the weight of the AD: 1 ~ 100.</p>
                </div>
            </div>
            <!--
            <div class="uk-form-row">
                <label class="uk-form-label">GEO:</label>
                <div class="uk-form-controls">
                    <div class="uk-autocomplete uk-form-icon" data-uk-autocomplete="{source:'/api/geo'}">
                        <i class="uk-icon-map-marker"></i>
                        <input type="text" class="uk-form-width-medium">
                    </div>
                    <p>Optional: the GEO of the AD.</p>
                </div>
            </div>
            -->
            <div class="uk-form-row">
                <div class="uk-form-controls">
                    <button type="submit" class="uk-button uk-button-primary"><i class="uk-icon-check"></i> {{ _('Save') }}</button>
                    &nbsp;
                    <button type="button" class="uk-button x-cancel"><i class="uk-icon-times"></i> {{ _('Cancel') }}</button>
                </div>
            </div>
        </fieldset>
    </form>

{% endblock %}
